<template>
  <div id="stu">
    <div class="select">
      <el-select
        v-model="searchInput"
        filterable
        clearable
        default-first-option
        remote
        reserve-keyword
        placeholder="Please enter a keyword"
        :remote-method="handleSearch"
        @change="searchChange"
        @focus="handleFocus"
        :loading="searchloading"
      >
        <el-option v-for="item in searchList" :key="item" :value="item" />
      </el-select>
      <el-button
        type="primary"
        :icon="Search"
        style="margin-left: 10px"
        @click="handleSearchbutton"
      >
        搜索
      </el-button>
      <el-button  style="margin-left:10px" @click="exportExcel">
        <template #icon>
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-Microsoft-Excel"></use>
            </svg>
        </template>
        <template #default>
           导出为Excel
        </template>
      </el-button>
      <el-button type="primary" style="margin-left: 10px" @click="addstu">
        添加
      </el-button>
    </div>
    <div class="table">
      <el-table
        :data="stulist"
        border
        style="width: 100%"
        v-loading="tableloading"
      >
        <el-table-column label="头像" width="70" align="center">
          <template #default="{ row, $index }">
            <el-image
              style="width: 50px; height: 50px"
              :src="imglist[$index]"
              :initial-index="$index"
              :preview-src-list="imglist"
              :zoom-rate="1.2"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="姓名"
          align="center"
          width="100px"
        />
        <el-table-column
          prop="class"
          label="班级"
          align="center"
          width="100px"
        />
        <el-table-column
          prop="degree"
          label="学历"
          align="center"
          width="100px"
        />
        <el-table-column
          prop="productUrl"
          label="项目"
          align="center"
          width="100px"
        />
        <el-table-column
          prop="cTime"
          label="时间"
          align="center"
          width="200px"
        />
        <el-table-column label="权限" align="center">
          <template #default="{ row }">
            <el-button type="" v-have:read="permission" @click="check(row)">查看</el-button>
          <el-button type="primary" v-have:edit="permission" :disabled="btn" @click="editStu(row)">
            编辑
          </el-button>
          <el-button type="danger" v-have:delete="permission" :disabled="btn" @click="delStu(row)">
            删除
          </el-button>
          </template>
        </el-table-column>
      </el-table>
      <stuDialog
      @ok="dialogOk"
      @cancel="dialogCancel"
      :dialogTitle="dialogTitle"
      :dialogAction="dialogAction"
      :reviewData="reviewData"
      ></stuDialog>
    </div>
    <!-- <div class="page"> -->
      <el-pagination hide-on-single-page background layout="prev, pager, next" :total="pagetotal" :page-size="pageData.count" :current-page="pageData.page"
      @current-change="handleSizeChange"
       />
    <!-- </div> -->
  </div>
</template>
<script setup>
import { onMounted, ref, computed,reactive } from "vue";
import * as api from "@/api/stu.js";
import { watch } from "vue";
import useUser from "../../../../store/user.js";
import stuDialog from "../../../../components/Dialog/index.vue";
import usedialog from "../../../../store/dialog.js";
import { Search } from "@element-plus/icons-vue";
import qee from "qf-export-excel"
import { ElMessage,ElMessageBox } from "element-plus";
import {useRouter} from 'vue-router'
let router = useRouter()
// import { pa } from "element-plus/es/locale";
let dialog = usedialog();
let user = useUser();
const searchList = ref([]);
const searchInput = ref();
const searchloading = ref(false);
//分页处理
let isSearch = false
let pageData =reactive({
  page: 1,
  count: 5,
  class: "",
});
// let currentPage = ref(1)
let pagetotal = ref();
let handleSizeChange = (pagesize)=>{
  pageData.page = pagesize
   if(isSearch){
    searchlist(searchInput.value, true,{page:pageData.page,count:pageData.count})
   }else{
    getStuList(pageData)
   }
}
const addstu = () => {
  //  console.log(dialog.dialogFormVisible);
  dialog.dialogFormVisible = true;
  dialogAction.value = "add";
};

let searchlist = async (key = "", isSelect = false,params={page:1,count:5}) => {
  isSearch = true
  isSelect && (tableloading.value = true);
  searchloading.value = true;
  try {
    let res = await api.searchStuApi({ key,page:params.page ,count:params.count});
    // console.log(res);
    searchList.value = new Set(res.data.data.map((item) => item.name));
    // console.log(searchList.value);
    isSelect && (pagetotal.value = res.data.total);
    searchloading.value = false;
    isSelect && (stulist.value = res.data.data) && (tableloading.value = false);
  } catch (error) {
    console.log(error);
    searchloading.value = false;
  }
};


let stulist = ref([]);
let tableloading = ref(false);
let getStuList = async (params = pageData) => {
  try {
    tableloading.value = true;
    let res = await api.getStuListApi(params);
    // console.log(res);
    pagetotal.value = res.data.total;
    stulist.value = res.data.data;
    // console.log(stulist.value);
    tableloading.value = false;
  } catch (error) {
    console.log(error);
    tableloading.value = false;
  }
};
onMounted(() => {
  getStuList(pageData);
});
let imglist = ref([]);
watch(stulist, (newval) => {
  imglist.value = newval.map((item) =>
    item.headimgurl
      ? item.headimgurl
      : "https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
  );
});

let handleSearch = (input) => {
  input && searchlist(input) &&(lastkey.value = input);  
};
let searchChange = (key) => {
  if(!key){
    isSearch = false
    pageData.page = 1
    getStuList(pageData)
  }else{
    pageData.page = 1
    searchlist(key,true,{page:pageData.page,count:pageData.count});
  }
};
let handleFocus = () => {
  searchList.value = [];
};
let lastkey = ref();
let handleSearchbutton = () => {
  searchInput.value = lastkey.value;
  pageData.page = 1
  searchlist(searchInput.value,true,{page:pageData.page,count:pageData.count})
  }

//按钮鉴权
const btn = ref(false);
const vHave = {
  mounted: (el, binding) => {
    // console.log(el);
    // console.log(binding.value);
    // console.log(binding.arg);
    let btnRequire = binding.arg;
    let userHave = binding.value;
    let result = userHave.includes(btnRequire);
    if (!result) {
      // el.parentNode.removeChild(el)
      btn.value = true;
    } else {
      btn.value = false;
    }
  },
};
// onMounted(() => {
  // console.log(user.$state.permission.value);
  // console.log(permission);
// });
let permission = computed(() => {
  let { buttons = [] } = user.$state.permission.value;
  return buttons;
});
//导出excel
let titleList = [{
    title: '头像',
    key: 'headimgurl'
}, 
{
    title: '姓名',
    key: 'name'
}, 
{
    title: '班级',
    key: 'class'
},
{
    title: '学历',
    key: 'degree'
},
{
    title: '项目地址',
    key: 'productUrl'
},
{
    title: '创建时间',
    key: 'cTime'
},
]
let exportExcel = () =>{
  qee(titleList,stulist.value,'学生信息表')
}
//回显
let dialogTitle = ref("添加学生信息");
let dialogAction = ref("add");
let reviewData = ref()
let editStu = (row) =>{
  console.log(row);
  dialog.dialogFormVisible = true;
  dialogTitle.value = '编辑学员信息'
  dialogAction.value = 'edit'
  reviewData.value = {...row}
}

//编辑 添加  删除 查看
let dialogOk =async (input)=>{
  // console.log(input);
  try {
    if(dialogAction.value == 'edit'){
       await api.updateStuApi(input)
       ElMessage.success('编辑成功')
    }else if(dialogAction.value == 'add'){
      await api.addStuApi(input)
      ElMessage.success('添加成功')
    }
    // console.log(res);
    getStuList()
  } catch (error) {
    console.log(error);
  }

}
let dialogCancel = ()=>{
  ElMessage.warn('取消成功')
}

let delStu = (row) =>{
  ElMessageBox.confirm(
    '确定删除吗',
    '警告⚠',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then( async () => {
      await api.delStuApi(row.sId)
      getStuList()
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'error',
        message: '取消删除',
      })
    })
}

let check = (row)=>{
   console.log(row);
   user.$state.dormitory.value = {...row}
  //  console.log(user.dormitory.value);
   router.push('dormitory')
}
</script>
<style scoped>
.table {
  margin: 10px 0 10px 0;
}

</style>
